package com.vhly.ddxdecompiler.dexreader.file.mixeditem;

import com.vhly.ddxdecompiler.dexreader.file.DexFile;
import com.vhly.ddxdecompiler.dexreader.io.DexInputStream;
import com.vhly.ddxdecompiler.dexreader.util.Leb128Utils;

import java.io.DataOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;

/**
 * Created by IntelliJ IDEA.
 * User: vhly
 * Date: 2009-10-15
 * Time: 12:47:10
 *
 * @author vhly[FR]
 */
public final class StringDataItem extends OffsettedItem {
    public String value;
    private DexFile dex;

    public StringDataItem(DexFile dexFile) {
        super(1, 0);
        dex = dexFile;
    }

    private static int writeSize(String value) {
        int ret = 0;
        if (value != null) {
            byte[] buf;
            try {
                buf = value.getBytes("UTF-8");
            } catch (UnsupportedEncodingException e) {
                buf = value.getBytes();
            }
            ret = buf.length;
            ret = Leb128Utils.unsignedLeb128Size(ret) + ret + 1;
        }
        // TODO test
        return ret;
    }

    /**
     * 读取数据
     *
     * @param din 输入流
     * @throws java.io.IOException 异常
     */
    public void read(DexInputStream din) throws IOException {
        offset = din.getOffset();
        dex.offsetCache.put(Integer.toString(offset), this);
        value = din.readUTFForDex();
//        System.out.println("[Debug] StringDataItem offset = " + offset + " strvalue = " + value);
    }

    public void write(DataOutputStream dout) throws IOException {
        dout.writeUTF(value);
    }
}
